<template>
  <div class="svg-detail-page">
    <!-- 头部导航 -->
    <div class="detail-header">
      <button @click="goBack" class="back-btn">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
          <path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        返回
      </button>
      <h1>SVG 详情</h1>
      <div class="header-actions">
        <button 
          @click="toggleFavorite"
          :class="['header-btn', { 'favorited': svgData.isFavorited }]"
          title="收藏"
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" 
                  :stroke="svgData.isFavorited ? 'none' : 'currentColor'" 
                  :fill="svgData.isFavorited ? 'currentColor' : 'none'"
                  stroke-width="2"/>
          </svg>
        </button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="detail-content" v-if="svgData">
      <!-- 左侧：SVG 预览 -->
      <div class="preview-section">
        <div 
          class="large-preview-container"
          :class="{ 'transparent-bg': selectedBackground === 'transparent' }"
          :style="{ backgroundColor: selectedBackground === 'transparent' ? 'transparent' : selectedBackground }"
        >
          <div class="svg-preview" v-html="svgData.content"></div>
        </div>
        
        <!-- 预览控制 -->
        <div class="preview-controls">
          <div class="size-controls">
            <label>预览尺寸：</label>
            <input 
              type="range" 
              v-model="previewSize" 
              min="50" 
              max="200" 
              step="10"
              class="size-slider"
            />
            <span>{{ previewSize }}%</span>
          </div>
          <div class="bg-controls">
            <label>背景：</label>
            <button 
              v-for="bg in backgrounds" 
              :key="bg.name"
              @click="selectedBackground = bg.value"
              :class="['bg-btn', { 'active': selectedBackground === bg.value }]"
              :style="{ background: bg.value }"
              :title="bg.name"
            ></button>
          </div>
        </div>
      </div>

      <!-- 右侧：详细信息 -->
      <div class="info-section">
        <div class="info-card">
          <div class="info-header">
            <h2>{{ svgData.displayName }}</h2>
            <span class="category-badge">{{ svgData.category }}</span>
          </div>
          
          <div class="info-content">
            <div class="info-item">
              <h3>描述</h3>
              <p>{{ svgData.description }}</p>
            </div>
            
            <div class="info-item">
              <h3>标签</h3>
              <div class="tags-list">
                <span v-for="tag in svgData.tags" :key="tag" class="tag">
                  {{ tag }}
                </span>
              </div>
            </div>
            
            <div class="info-item">
              <h3>属性</h3>
              <div class="properties-grid">
                <div class="property">
                  <label>文件名：</label>
                  <span>{{ svgData.name }}</span>
                </div>
                <div class="property">
                  <label>尺寸：</label>
                  <span>{{ svgDimensions.width }} × {{ svgDimensions.height }}</span>
                </div>
                <div class="property">
                  <label>大小：</label>
                  <span>{{ formatFileSize(svgData.size) }}</span>
                </div>
                <div class="property">
                  <label>上传时间：</label>
                  <span>{{ formatDate(svgData.uploadDate) }}</span>
                </div>
              </div>
            </div>
            
            <div class="info-item">
              <h3>SVG 代码</h3>
              <div class="code-preview">
                <pre><code>{{ formatSvgCode(svgData.content) }}</code></pre>
                <button @click="copySvgCode" class="copy-btn">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2" stroke="currentColor" stroke-width="2"/>
                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  复制
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button @click="downloadSvg" class="action-btn primary">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2"/>
              <polyline points="7,10 12,15 17,10" stroke="currentColor" stroke-width="2"/>
              <line x1="12" y1="15" x2="12" y2="3" stroke="currentColor" stroke-width="2"/>
            </svg>
            下载 SVG
          </button>
          <button @click="editSvg" class="action-btn secondary">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2"/>
              <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2"/>
            </svg>
            编辑
          </button>
          <button @click="shareSvg" class="action-btn outline">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <circle cx="18" cy="5" r="3" stroke="currentColor" stroke-width="2"/>
              <circle cx="6" cy="12" r="3" stroke="currentColor" stroke-width="2"/>
              <circle cx="18" cy="19" r="3" stroke="currentColor" stroke-width="2"/>
              <line x1="8.59" y1="13.51" x2="15.42" y2="17.49" stroke="currentColor" stroke-width="2"/>
              <line x1="15.41" y1="6.51" x2="8.59" y2="10.49" stroke="currentColor" stroke-width="2"/>
            </svg>
            分享
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading-state">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const svgData = ref(null)
const previewSize = ref(100)
const selectedBackground = ref('transparent')

// 背景选项
const backgrounds = [
  { name: '透明', value: 'transparent' },
  { name: '白色', value: '#ffffff' },
  { name: '黑色', value: '#000000' },
  { name: '浅灰', value: '#f5f5f5' },
  { name: '深灰', value: '#333333' }
]

// 计算属性
const svgDimensions = computed(() => {
  if (!svgData.value?.content) return { width: 0, height: 0 }
  
  const match = svgData.value.content.match(/width="(\d+)"\s+height="(\d+)"/)
  if (match) {
    return {
      width: parseInt(match[1]),
      height: parseInt(match[2])
    }
  }
  
  const viewBoxMatch = svgData.value.content.match(/viewBox="[^"]*\s+(\d+)\s+(\d+)"/)
  if (viewBoxMatch) {
    return {
      width: parseInt(viewBoxMatch[1]),
      height: parseInt(viewBoxMatch[2])
    }
  }
  
  return { width: 'auto', height: 'auto' }
})

// 生命周期
onMounted(() => {
  loadSvgData()
})

// 方法
const loadSvgData = () => {
  // 从 localStorage 或路由参数获取数据
  const savedData = localStorage.getItem('selectedSvgDetail')
  if (savedData) {
    svgData.value = JSON.parse(savedData)
  } else {
    // 如果没有数据，返回主页
    router.push('/')
  }
}

const goBack = () => {
  router.go(-1)
}

const toggleFavorite = () => {
  if (svgData.value) {
    svgData.value.isFavorited = !svgData.value.isFavorited
    // 这里可以添加保存到后端的逻辑
  }
}

const downloadSvg = () => {
  if (!svgData.value) return
  
  const blob = new Blob([svgData.value.content], { type: 'image/svg+xml' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = svgData.value.name
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

const editSvg = () => {
  // 跳转到编辑页面
  localStorage.setItem('selectedSvgForEdit', JSON.stringify(svgData.value))
  router.push('/preview')
}

const shareSvg = () => {
  if (navigator.share) {
    navigator.share({
      title: svgData.value.displayName,
      text: svgData.value.description,
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href)
    alert('链接已复制到剪贴板')
  }
}

const copySvgCode = () => {
  if (svgData.value?.content) {
    navigator.clipboard.writeText(svgData.value.content)
    alert('SVG 代码已复制到剪贴板')
  }
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (date) => {
  if (!date) return '未知'
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const formatSvgCode = (content) => {
  if (!content) return ''
  // 简单的代码格式化
  return content.replace(/></g, '>\n<').replace(/\s+/g, ' ')
}
</script>

<style scoped>
.svg-detail-page {
  min-height: 100vh;
  background: #f8fafc;
}

.detail-header {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 1rem 2rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  background: white;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s;
}

.back-btn:hover {
  background: #f1f5f9;
  border-color: #cbd5e1;
}

.detail-header h1 {
  margin: 0;
  font-size: 1.5rem;
  color: #1e293b;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
}

.header-btn {
  width: 40px;
  height: 40px;
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  color: #64748b;
}

.header-btn:hover {
  background: #f1f5f9;
}

.header-btn.favorited {
  background: #fef2f2;
  border-color: #fca5a5;
  color: #dc2626;
}

.detail-content {
  padding: 2rem;
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 2rem;
  max-width: 1400px;
  margin: 0 auto;
}

.preview-section {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.large-preview-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  border: 2px dashed #e2e8f0;
  border-radius: 0.5rem;
  margin-bottom: 2rem;
  position: relative;
}

.large-preview-container.transparent-bg {
  background-image: 
    linear-gradient(45deg, #f1f5f9 25%, transparent 25%), 
    linear-gradient(-45deg, #f1f5f9 25%, transparent 25%), 
    linear-gradient(45deg, transparent 75%, #f1f5f9 75%), 
    linear-gradient(-45deg, transparent 75%, #f1f5f9 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
}

.svg-preview {
  transform: scale(calc(v-bind(previewSize) / 100));
  transition: transform 0.3s ease;
}

.svg-preview svg {
  max-width: 100%;
  max-height: 100%;
}

.preview-controls {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.size-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.size-slider {
  flex: 1;
}

.bg-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.bg-btn {
  width: 30px;
  height: 30px;
  border: 2px solid #e2e8f0;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.bg-btn[style*="transparent"] {
  background-image: 
    linear-gradient(45deg, #f1f5f9 25%, transparent 25%), 
    linear-gradient(-45deg, #f1f5f9 25%, transparent 25%), 
    linear-gradient(45deg, transparent 75%, #f1f5f9 75%), 
    linear-gradient(-45deg, transparent 75%, #f1f5f9 75%);
  background-size: 8px 8px;
  background-position: 0 0, 0 4px, 4px -4px, -4px 0px;
}

.bg-btn.active {
  border-color: #3b82f6;
  transform: scale(1.1);
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.info-card {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.info-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1.5rem;
}

.info-header h2 {
  margin: 0;
  color: #1e293b;
}

.category-badge {
  background: #e2e8f0;
  color: #64748b;
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.875rem;
  font-weight: 500;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.info-item h3 {
  margin: 0 0 0.5rem 0;
  color: #374151;
  font-size: 1rem;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.tag {
  background: #f1f5f9;
  color: #475569;
  padding: 0.25rem 0.75rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
}

.properties-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.75rem;
}

.property {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.property label {
  font-weight: 500;
  color: #64748b;
  font-size: 0.875rem;
}

.property span {
  color: #1e293b;
}

.code-preview {
  position: relative;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  padding: 1rem;
  max-height: 200px;
  overflow-y: auto;
}

.code-preview pre {
  margin: 0;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 0.8rem;
  line-height: 1.5;
  color: #475569;
}

.copy-btn {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  padding: 0.5rem;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 0.25rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.875rem;
  color: #64748b;
}

.copy-btn:hover {
  background: #f1f5f9;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.action-btn.primary {
  background: #3b82f6;
  color: white;
  border: none;
}

.action-btn.primary:hover {
  background: #2563eb;
}

.action-btn.secondary {
  background: #10b981;
  color: white;
  border: none;
}

.action-btn.secondary:hover {
  background: #059669;
}

.action-btn.outline {
  background: white;
  color: #64748b;
  border: 1px solid #e2e8f0;
}

.action-btn.outline:hover {
  background: #f1f5f9;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  gap: 1rem;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e2e8f0;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .detail-content {
    grid-template-columns: 1fr;
    gap: 1rem;
    padding: 1rem;
  }
  
  .detail-header {
    padding: 1rem;
  }
  
  .properties-grid {
    grid-template-columns: 1fr;
  }
}
</style>
